package com.example.bookstore.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.bookstore.common.BaseContext;
import com.example.bookstore.common.Result;
import com.example.bookstore.entity.Admin;
import com.example.bookstore.entity.User;
import com.example.bookstore.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    AdminService adminService;
    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping("/login")
    public Result<String> login(@RequestBody Map<String,String> form, HttpServletRequest request){
        String username = form.get("username");
        String password = form.get("password");
        Admin admin = adminService.login(username, password);
        if (admin!=null){
            request.getSession().setAttribute("admin",admin);
            String json= JSON.toJSONString(admin);
            redisTemplate.opsForValue().set(username,json,5, TimeUnit.MINUTES);//会话5分钟过期
            return Result.success("登录成功");
        }
        return Result.error("登录失败");
    }
    @GetMapping()
    public Admin getAdmin(HttpServletRequest request){
        Object ob = request.getSession().getAttribute("admin");
        Admin admin=(Admin) ob;
        String adminName = admin.getAdminName();
        String jsonString = (String)  redisTemplate.opsForValue().getAndExpire(adminName,5, TimeUnit.MINUTES);//获取同时更新缓存时间
        if (jsonString==null){
            request.getSession().removeAttribute("admin");
            return null;
        }
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        Admin redis = JSON.toJavaObject(jsonObject,Admin.class);
        return redis;
    }
    @GetMapping("/logout")
    public Result<String> logoutAdmin(HttpSession session){
        Admin admin = (Admin) session.getAttribute("admin");
        redisTemplate.delete(admin.getAdminName());
        session.removeAttribute("admin");
        return Result.success("退出成功");
    }
}
